/**
 * 
 */
package com.planner.core.action.search;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Required;

import com.planner.core.action.base.AbstractBaseAction;
import com.planner.core.action.search.form.SearchResult;
import com.planner.core.action.search.form.SearchRouteForm;
import com.planner.core.dao.NodeNotFoundException;
import com.planner.core.dao.stub.StubUtil;
import com.sangharsh.core.algo.Journey;
import com.sangharsh.core.algo.Route;
import com.sangharsh.core.algo.Vertex;
import com.sangharsh.core.algo.location.Location;
import com.sangharsh.webapp.service.RouteNotFoundException;
import com.sangharsh.webapp.service.RouteSearchService;

/**
 * @author Sangharsh
 *
 */
public class SearchRouteAction extends AbstractBaseAction {

	private static final Log LOG = LogFactory.getLog(SearchRouteAction.class);
	
	private RouteSearchService searchService;
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws NodeNotFoundException {
		SearchRouteForm searchForm = (SearchRouteForm)form;
		setStaticData(searchForm);
		if(searchForm.getFrom() != null && searchForm.getTo() != null){
			try {
				List<Route<Journey>> routes = searchService.getRoute(new Vertex(searchForm.getFromStr(), searchForm.getFromCode(), Location.getLocation(searchForm.getFrom())), new Vertex(searchForm.getToStr(), searchForm.getToCode(), Location.getLocation(searchForm.getTo())));
				searchForm.setResult(new SearchResult<Route<Journey>>(routes));
			} catch (RouteNotFoundException e) {
				
			}
			
		}
		LOG.info("Search Route");
		return mapping.findForward(SUCCESS_FORWARD);
	}
	

	private void setStaticData(SearchRouteForm routeForm) {
		routeForm.setTypes(StubUtil.getNodeTypes());
	}
	
	/**
	 * @param searchService the searchService to set
	 */
	@Required
	public void setSearchService(RouteSearchService searchService) {
		this.searchService = searchService;
	}
	
}